package com.aliengen.thingple.cmc168mwithservice;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class Common {
	//Func:BCC
	public static byte bcc(byte[] data,int offset,int size)
	{
		byte b = 0;
		for(int i = 0; i < size; i++)
		{
			b ^= data[offset + i];
		}
		return b;
	}
	//Func:hex2Word +	
	private static synchronized String hex2Word(byte b) 
	{
		return ("" + "0123456789ABCDEF".charAt(0x0f & b >> 4) + "0123456789ABCDEF".charAt(b & 0x0f));
	}
	//Func:arrByte2String +    
	public static String arrByte2String(byte[] buf,int offset,int size)
	{
		if (size > 64) size = 64;
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < size; i++)
		{
			sb.append(hex2Word(buf[offset+i]));
			if(i < (buf.length - 1))
				sb.append(' ');
		}
		return sb.toString();
	}
	//Func:hexToInt +   
	static int hexToInt(char ch)
	{
		if ('a' <= ch && ch <= 'f') { return ch - 'a' + 10; }
		if ('A' <= ch && ch <= 'F') { return ch - 'A' + 10; }
		if ('0' <= ch && ch <= '9') { return ch - '0'; }
		throw new IllegalArgumentException(String.valueOf(ch));
	}	
	//Func:hexToAscii +
	public String hexToAscii(String s) throws IllegalArgumentException
	{
		int n = s.length();
		StringBuilder sb = new StringBuilder(n / 2);
		for (int i = 0; i < n; i += 2)
		{
			char a = s.charAt(i);
			char b = s.charAt(i + 1);
			sb.append((char) ((hexToInt(a) << 4) | hexToInt(b)));
		}
		return sb.toString();
	} 
	//Func:hexStr2Bytes + 
	public static void hexStr2Bytes(String src,byte[] desc,int offset,int max)
	{
		int m=0,n=0;
		int l;
		src = src.replaceAll(" ", "");
		l = src.length()/2;        
		if(l>max)l=max;
		String str1;
		for (int i = 0; i < l; i++)
		{
			m=i*2+1;
			n=m+1;
			str1 = "0x" + src.substring(i*2, m) + src.substring(m,n);
			try
			{
				desc[offset+i] = Integer.decode(str1).byteValue() ;
			}catch(Exception ex){}
		}
	}
	//Func:chekSum
	public static short checkSum(byte[] b,int offset, int size){
		short nRet = 0;
		for (int i = 0; i < size; i++){
			nRet += b[i + offset];
		}
		return nRet;
	}
	public static void memcpy(
			byte[] desBuf, byte[] srcBuf, int desOffset,int srcOffset, int count)
	{
		for(int i = 0; i < count; i++){
    		desBuf[desOffset + i] = srcBuf[srcOffset + i];
    	}
	}
	//Func:Byte2Int
	public static int Byte2Int(byte b){
		return (int)b < 0?(int)b + 256 : (int)b;
	}
}
